package com.pactera.asmp.server.common.websocket.config;

import com.pactera.asmp.server.common.logprint.utils.StringUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class ServerConfig  implements ApplicationListener<WebServerInitializedEvent> {
    @Value("${server.port}")
    private int serverPort;

    @Value("${server.instance.ip}")
    private String serverIp;

    public String getUrl() {
        String ip = serverIp;
        if(StringUtils.isEmpty(ip)){
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
                ip = null;
            }
        }
        if(StringUtils.isEmpty(ip)) return null;
        return ip.replace(".","_") +"_"+this.serverPort;
    }
 
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }
 
}